// 封装购物车模块
import {defineStore} from 'pinia'
import {computed, ref} from 'vue'
import {useUserStore} from "@/stores/user";
import {insertCartAPI, findNewCartListAPI, delCartAPI} from '@/apis/cart'

export const useCartStroe = defineStore('cart', () => {
    const userStore = useUserStore()
    const isLogin = computed(() => userStore.userInfo.token)

    // 1.定义state-cartList
    const cartList = ref([])

    // 获取最新购物车列表
    const updateNewList = async () => {
        const res = await findNewCartListAPI()
        // console.log(res)
        cartList.value = res.result
    }

    // 2.定义action -addCart
    const addCart = async (goods) => {
        const {skuId, count} = goods
        if (isLogin.value) {
            await insertCartAPI({skuId, count})
            await updateNewList()
        } else {

            // 添加购物车操作
            // 已添加过 count + 1
            // 未添加过, 直接push
            // 通过匹配床底过来的商品对象中的skuid能不能再cartlist中找到,找到了就是添加过
            const item = cartList.value.find((item) => goods.skuId === item.skuId)
            if (item) {
                // 找到后
                item.count++
            } else {
                // 未找到
                cartList.value.push(goods)
            }
        }
    }

    // 添加一个删除action
    const delCart = async (skuId) => {
        // 思路
        // 1.找到要删除项的下标值
        // 2.使用数组的过滤方法
        if (isLogin.value) {
            await delCartAPI([skuId])
            await updateNewList()
        } else {
            const idx = cartList.value.findIndex((item) => skuId === item.id)
            cartList.value.splice(idx, 1)
        }
    }

    // 清除购物车
    const clearCart = () => {
        cartList.value = []
    }


    // 计算属性
    // 1.总的数量 所有项的count之和
    const allCount = computed(() => cartList.value.reduce((a, c) => a + c.count, 0))

    // 2.总价,所有项的count*price之和
    const allPrice = computed(() => cartList.value.reduce((a, c) => a + c.count * c.price, 0) // 这里设置reduce的第二个参数是为了将0赋值给a
    )

    // 单选功能
    const singleCheck = (skuId, selected) => {
        // 通过skuId找到要修改的那一项，然后把他的selected修改为传过来的selected
        const item = cartList.value.find((item) => item.skuId === skuId)
        item.seleted = selected
    }

    // 是否全选
    const isAll = computed(() => cartList.value.every((item) => item.seleted))

    // 全选功能
    // 将cartList中的每一项的seleted都设置为当前的全选框状态
    const allCheck = (seleted) => {
        cartList.value.forEach(item => item.seleted = seleted)
    }

    /// 已选择商品数量
    const selectedCount = computed(() => cartList.value.filter(item => item.seleted).reduce(((a, c) => a + c.count), 0))

    // 已选择商品的价钱合计
    const selectedCountPrice = computed(() => cartList.value.filter(item => item.seleted).reduce(((a, c) => a + c.count * c.price), 0))


    return {
        cartList, allCount, allPrice, isAll, selectedCount, selectedCountPrice, addCart, delCart, singleCheck, allCheck,
        clearCart, updateNewList
    }
}, {
    persist: true,
})
